


<template>
  <MainLayout>
    <router-view></router-view>
    <div class="third-party-authorization">
    <h2>第三方授权</h2>

    <!-- 添加用户表单 -->
    <el-form :inline="true" class="add-user-form">
      <el-form-item v-if="!showAdvancedSearch">
        <el-input v-model="searchQuery" placeholder="请输入用户名或手机号" />
      </el-form-item>
      <el-form-item>
        <!-- 条件查询绑定 -->
        <template v-if="showAdvancedSearch">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="用户名" :label-width="labelWidth">
                <el-input v-model="paginationParams.userName" placeholder="请输入用户名" :style="{ width: inputWidth }" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="真实姓名" :label-width="labelWidth">
                <el-input v-model="paginationParams.realName" placeholder="请输入真实姓名" :style="{ width: inputWidth }" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="手机号" :label-width="labelWidth">
                <el-input v-model="paginationParams.phone" placeholder="请输入手机号" :style="{ width: inputWidth }" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="状态" :label-width="labelWidth">
                <el-select v-model="paginationParams.status" placeholder="请选择状态" style="width: 120px;">
                  <el-option label="启用" :value="0" />
                  <el-option label="禁用" :value="1" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button type="text" style="width: 80px;" @click="toggleAdvancedSearch">
          {{ showAdvancedSearch ? '收起' : '高级搜索' }}
        </el-button>
      </el-form-item>
    </el-form>
    <el-form :inline="true" class="add-user-form" style="float: right;">
      <el-form-item>
        <el-button type="primary" @click="openAddDialog">添加用户</el-button>
        <el-button type="danger" :disabled="selectedUsers.length === 0" @click="batchDelete">批量删除</el-button>
      </el-form-item>
    </el-form>

    <!-- 用户显示列表 -->
    <el-table
        :data="paginatedUsers"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="userName" label="用户名" />
      <el-table-column prop="realName" label="真实姓名" />
      <el-table-column prop="password" label="密码" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
            {{ scope.row.status === 0 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click.stop="editUser(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        class="pagination"
        background
        layout="prev, pager, next"
        :total="users.length"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
    />

    <!-- 编辑用户模态框 -->
    <el-dialog v-model="isEditing" title="编辑用户" width="40%" class="custom-dialog">
      <el-form :model="editingUser" label-width="100px" label-position="left" class="custom-form">
        <el-form-item label="用户名">
          <el-input v-model="editingUser.userName" placeholder="请输入用户名" class="custom-input" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="editingUser.realName" placeholder="请输入真实姓名" class="custom-input" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="editingUser.password" type="password" placeholder="请输入密码" class="custom-input" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editingUser.phone" placeholder="请输入手机号" class="custom-input" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editingUser.status" placeholder="请选择状态" class="custom-select">
            <el-option label="启用" :value="0" />
            <el-option label="禁用" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelEdit" class="custom-button">取消</el-button>
        <el-button type="primary" @click="saveEdit" class="custom-button">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新增用户模态框 -->
    <el-dialog v-model="isAdding" title="新增用户" width="40%" class="custom-dialog">
      <el-form :model="newUser" label-width="100px" label-position="left" class="custom-form">
        <el-form-item label="用户名">
          <el-input v-model="newUser.userName" placeholder="请输入用户名" class="custom-input" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="newUser.realName" placeholder="请输入真实姓名" class="custom-input" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="newUser.password" type="password" placeholder="请输入密码" class="custom-input" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="newUser.phone" placeholder="请输入手机号" class="custom-input" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelAdd" class="custom-button">取消</el-button>
        <el-button type="primary" @click="saveAdd" class="custom-button">保存</el-button>
      </template>
    </el-dialog>

    <!-- 详情用户模态框 -->
    <el-dialog v-model="isViewingDetail" title="用户详情" width="40%" class="custom-dialog">
      <el-form :model="userDetail" label-width="100px" label-position="left" class="custom-form">
        <el-form-item readonly label="用户名">
          <el-input v-model="userDetail.userName" readonly class="custom-input" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="userDetail.realName" readonly class="custom-input" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="userDetail.phone" readonly class="custom-input" />
        </el-form-item>
        <el-form-item label="状态">
          <el-tag :type="userDetail.status === 0 ? 'success' : 'danger'">
            {{ userDetail.status === 0 ? '启用' : '禁用' }}
          </el-tag>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isViewingDetail = false" class="custom-button">关闭</el-button>
      </template>
    </el-dialog>

  </div>
  </MainLayout>

</template>

<script>
import MainLayout from '@/layouts/MainLayout.vue'
export default {
  components: {
    MainLayout
  },
  data() {
    return {
      // 模态框样式-数据绑定
      labelWidth: '70px',
      inputWidth: '100%',
      users: [],
      // 新增-用户数据绑定 isAdding newUser
      isAdding: false,
      newUser: {
        userName: '',
        password: '',
        realName: '',
        phone: '',
        status: 0,
        avatar: ''
      },
      // 编辑-用户数据绑定 isEditing editingUser
      isEditing: false,
      editingUser: {
        id: null,
        userName: '',
        password: '',
        realName: '',
        phone: '',
        status: 1,
        avatar: ''
      },
      // 分页-数据绑定 
      currentPage: 1,
      pageSize: 5,
      // 批量删除-数据绑定 
      selectedUsers: [],
      // 模糊查询-数据绑定
      searchQuery: '',
      // 条件查询-数据绑定 showAdvancedSearch paginationParams
      showAdvancedSearch: false,
      paginationParams: {
        pageNo: 1,
        pageSize: 10,
        userName: '',
        phone: '',
        realName: '',
        status: null
      },
      // 详情-数据绑定 isViewingDetail userDetail
      isViewingDetail: false,
      userDetail: {}
    };
  },
  computed: {
    // 用户显示列表-分页计算属性
    paginatedUsers() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.users.slice(start, end);
    }
  },
  methods: {
    // 新增用户按钮
    openAddDialog() {
      this.isAdding = true;
    },
    // 新增取消按钮
    cancelAdd() {
      this.isAdding = false;
      this.newUser = {
        userName: '',
        password: '',
        realName: '',
        phone: '',
        status: 0,
        avatar: ''
      };
    },
    // 新增保存按钮
    async saveAdd() {
      try {
        const response = await fetch('http://localhost:8090/user/C', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            userName: this.newUser.userName,
            realName: this.newUser.realName,
            password: this.newUser.password,
            phone: this.newUser.phone,
            status: this.newUser.status
          })
        });

        const data = await response.json();
        if (data.code == 200) {
          this.cancelAdd();
          this.$message.success('用户添加成功');
          this.fetchUsers();
        } else {
          this.$message.error('用户添加失败');
        }
      } catch (err) {
        console.error('添加用户失败:', err);
        this.$message.error('添加用户出错');
      }
    },
    // 编辑按钮
    editUser(user) {
      this.isEditing = true;
      this.editingUser = { ...user };
    },
    // 编辑取消按钮
    cancelEdit() {
      this.isEditing = false;
      this.editingUser = {
        id: null,
        userName: '',
        realName: '',
        password: '',
        phone: '',
        status: 1,
        avatar: ''
      };
    },
    // 编辑保存按钮
    async saveEdit() {
      try {
        const response = await fetch('http://localhost:8090/user/UById', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            id: this.editingUser.id,
            userName: this.editingUser.userName,
            realName: this.editingUser.realName,
            password: this.editingUser.password,
            phone: this.editingUser.phone,
            status: this.editingUser.status
          })
        });

        const data = await response.json();
        if (data.code == 200) {
          this.cancelEdit();
          this.$message.success('用户编辑成功');
          this.fetchUsers();
        } else {
          this.$message.error('用户编辑失败');
        }
      } catch (err) {
        console.error('编辑用户失败:', err);
        this.$message.error('编辑用户出错');
      }
    },
    // 删除按钮
    async deleteUser(userId) {
      try {
        const response = await fetch(`http://localhost:8090/user/DById/${userId}`, {
          method: 'GET'
        });

        const data = await response.json();
        if (data.code == 200) {
          this.users = this.users.filter(user => user.id !== userId);
          this.$message.success('用户删除成功');
        } else {
          this.$message.error('用户删除失败');
        }
      } catch (err) {
        console.error('删除用户失败:', err);
        this.$message.error('删除用户出错');
      }
    },
    // 搜索相关方法1
    toggleAdvancedSearch() {
      this.showAdvancedSearch = !this.showAdvancedSearch;
      if (!this.showAdvancedSearch) {
        this.paginationParams.realName = '';
        this.paginationParams.status = null;
      }
    },
    // 搜索相关方法2
    onSearch() {
      const isPhoneNumber = /^1[3-9]\d{9}$/.test(this.searchQuery);

      if (isPhoneNumber) {
        this.paginationParams.phone = this.searchQuery;
      } else if (this.searchQuery.trim() !== '') {
        this.paginationParams.userName = this.searchQuery;
      }

      this.fetchUsers();
    },
    // 获取用户数据
    async fetchUsers() {
      try {
        const response = await fetch('http://localhost:8090/user/P', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            pageNo: this.paginationParams.pageNo,
            pageSize: this.paginationParams.pageSize,
            userName: this.paginationParams.userName,
            phone: this.paginationParams.phone,
            realName: this.paginationParams.realName,
            status: this.paginationParams.status
          })
        });

        if (!response.ok) throw new Error('网络响应错误');

        const data = await response.json();

        if (data.code == 200) {
          this.users = data.data.records.map(user => ({
            id: user.id,
            userName: user.userName,
            realName: user.realName,
            password: user.password,
            phone: user.phone,
            status: user.status
          }));
        }
      } catch (err) {
        console.error('获取用户数据失败:', err);
      }
    },
    // 分页方法
    handlePageChange(page) {
      this.currentPage = page;
      this.paginationParams.pageNo = page;
      this.fetchUsers();
    },
    // 批量删除相关方法
    async batchDelete() {
      if (this.selectedUsers.length === 0) {
        this.$message.warning('请选择要删除的用户');
        return;
      }

      try {
        const userIds = this.selectedUsers.map(user => user.id);
        const response = await fetch('http://localhost:8090/user/DByIds', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(userIds)
        });

        const data = await response.json();
        if (data.code == 200) {
          this.users = this.users.filter(user => !userIds.includes(user.id));
          this.selectedUsers = [];
          this.$message.success('批量删除成功');
        } else {
          this.$message.error('批量删除失败');
        }
      } catch (err) {
        console.error('批量删除失败:', err);
        this.$message.error('批量删除出错');
      }
    },
    // ✅ 新增：处理表格选中变化
    handleSelectionChange(selectedUsers) {
      console.log('选中用户:', selectedUsers);
      this.selectedUsers = selectedUsers;
    },
    // ✅ 详情：处理表格行点击
    async handleRowClick(row) {
  try {
    const response = await fetch(`http://localhost:8090/role/RById/${row.id}`, {
      method: 'GET'
    });
    
    const data = await response.json();
    if (data.code == 200) {
      this.roleDetail = data.data;
      this.isViewingDetail = true;
      this.$message.success('获取角色详情成功');
    } else {
      this.$message.error('获取角色详情失败');
    }
  } catch (err) {
    console.error('获取角色详情失败:', err);
    this.$message.error('获取角色详情出错');
  }
}

  },

  mounted() {
    this.fetchUsers();
  }
};
</script>

<style scoped>/* 保持原有样式不变 */
.user-management {
  width: 100%;
  min-height: 100vh;
  margin: 0;
  padding: 30px;
  background-color: #fff;
  padding-bottom: 100px;
}

.pagination {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 30px;
  margin-top: 24px;
  justify-content: center;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.custom-dialog {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.custom-form {
  padding: 20px;
}

.custom-input {
  width: 100%;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.3s ease;
}

.custom-input:hover {
  border-color: #409eff;
}

.custom-select {
  width: 100%;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.3s ease;
}

.custom-select:hover {
  border-color: #409eff;
}

.custom-button {
  border-radius: 4px;
  padding: 10px 20px;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.custom-button:hover {
  background-color: #409eff;
  color: #fff;
}

.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 8px 8px 0 0;
  padding: 16px;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  padding: 16px;
  border-top: 1px solid #ebeef5;
  background-color: #f5f7fa;
  box-shadow: none;
}

.user-management h2 {
  margin-top: 10px;
  margin-bottom: 24px;
  font-size: 24px;
  font-weight: 500;
  text-align: left;
}
</style>